<?php
// +----------------------------------------------------------------------
// | Description: 积分model
// +----------------------------------------------------------------------
// | Author: linchuangbin <linchuangbin@honraytech.com>
// +----------------------------------------------------------------------

namespace app\v2\model;

use think\Db;

use think\Model;
class Score extends Model 
{	
    
    /**
     *  默认时间戳是字段  creat_time
     *  默认时间戳是格式  datetime
     */
	protected $name = 'score';
    protected $createTime = "create_time";
    protected $updateTime = false;
	protected $autoWriteTimestamp = 'datetime';

	/**
	 * 查询余额
	 * @zwr
	 * @DateTime 2017-7-5 14:41:16
	 * @param    int        $uid   用户uid
	 * @return   numeric            余额度
	 */
	public function balance($uid)
	{ 
		$score = $this->where('uid',$uid)->value('score');
		if(is_null($score)){
			$param['uid'] = $uid;
			$param['score'] = '0.00';
			$res = $this->data($param)->allowField(true)->save();
			return $this->balance($uid);
		}
		return $this->where('uid',$uid)->value('score');
	}
	/**
	 * 积分操作分发方法
	 * @zwr
	 * @DateTime 2017-7-5 14:36:16
	 * @param    int           $uid      用户id
	 * @param    numeric       $value    积分变动值
	 * @param    string        $type     积分变动类型  加积分传 setInc  减 setDec
	 * @return   bool                          
	 */
	public function handle($uid,$value,$type)
	{         

        if(!$uid){
			$this->error = "请选择用户";
			return false;
        }
		if(!is_numeric($value)&& $value < 0){
			$this->error = "积分值必须为正数";
			return false;
		}


        switch ($type) {
        	case 'setInc':
        		return $this->setIncScore($uid,$value);
        		break;
        	case 'setDec':
        		return $this->setDecScore($uid,$value);
        		break;        	
        	default:
        		$this->error = "操作类型错误";
        		return false;
        		break;
        }
	}
	/**
	 * 加积分操作方法
	 * @zwr
	 * @DateTime 2017-7-5 14:38:56
	 * @param    int         $uid      积分变动用户id
	 * @param    numeric     $value    积分变动值
	 * @return   bool  
	 */
	private function setIncScore($uid,$value)
	{	
		$res = $this->where('uid',$uid)->setInc('score', $value);
		if(!$res){
    		$this->error = "加余额失败";
    		return false;			
		}
		return true;
	}
	/**
	 * 减积分操作方法
	 * @zwr
	 * @DateTime 2017-7-5 14:38:56
	 * @param    int         $uid      积分变动用户id
	 * @param    numeric     $value    积分变动值
	 * @return   bool  
	 */	
	private function setDecScore($uid,$value)
	{
		$res = $this->where('uid',$uid)->setDec('score', $value);
		if(!$res){
    		$this->error = "减余额失败";
    		return false;			
		}
		return true;		
	}
}